package uabc.arduino.graficas;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.imageio.ImageIO;
import javax.swing.JComponent;

import uabc.arduino.archivo.CsvManager;
import uabc.arduino.componentes.ChartConfiguration;
import uabc.arduino.elementos.SerieConfiguration;

public class JFImagen extends JFrame implements Observer {

	private String titulo;
	private String unidades;
	private ChartConfiguration chartConf;
	private ArrayList<SerieConfiguration> series;
	private CsvManager csvManager;
	private boolean play;
	private boolean saveFile;
	private String nombreImagen;
	private String archivoConfiguracion;

	private HashMap<String, JLabel> lblsValores;

	public JFImagen(ChartConfiguration chartConf, CsvManager csvManager,
			boolean saveFile) {
		this.titulo = chartConf.getTitulo();
		this.unidades = chartConf.getUnidades();
		this.chartConf = chartConf;
		this.csvManager = csvManager;
		this.play = true;
		this.saveFile = saveFile;
		series = cloneList(chartConf.getConfiguraciones());
		this.nombreImagen = chartConf.getImagen();
		this.archivoConfiguracion = chartConf.getArchivoConfiguracion();

		setTitle(titulo);
		generarEtiquetas();
		ImageComponent component = new ImageComponent("imagenes/"
				+ nombreImagen);
		setSize(component.getWidth(), component.getHeight());
		add(component);
	}

	public static ArrayList<SerieConfiguration> cloneList(
			ArrayList<SerieConfiguration> list) {
		ArrayList<SerieConfiguration> clone = new ArrayList<SerieConfiguration>(
				list.size());
		for (SerieConfiguration item : list)
			clone.add((SerieConfiguration) item.clone());
		return clone;
	}

	@Override
	public void update(Observable o, Object arg) {
		if (play) {
			try {
				String cadena = (String) arg;
				if (cadena.startsWith("V:")) {
					cadena = cadena.substring(2);
					HashMap<String, Double> valores = decodificar(cadena);
					String[] csv = new String[series.size() + 2];
					int count = 2;
					csv[0] = (new Date().toString());
					csv[1] = new SimpleDateFormat("HH:mm:ss")
							.format(new Date());
					for (SerieConfiguration s : series) {
						double d = valores.get(s.getID());
						JLabel lbl = getLblsValores().get(s.getID());
						lbl.setText(d+" "+lbl.getName());
						csv[count] = String.valueOf(d);
						count++;
					}
					if (saveFile)
						csvManager.escribir(csv);
				}
			} catch (Exception e) {
				// System.err.println(e.toString());
			}
		}
	}

	public HashMap<String, Double> decodificar(String cadena) {
		String[] entradas = cadena.split("-");
		HashMap<String, Double> mapa = new HashMap<String, Double>();
		for (int i = 0; i < entradas.length; i++) {
			String[] entrada = entradas[i].split(":");
			mapa.put(entrada[0], Double.parseDouble(entrada[1]));
		}
		return mapa;
	}

	public void stop() {
		if (csvManager != null)
			csvManager.cerrar();
	}

	public void generarEtiquetas() {
		ArrayList<String> lineas = readFile(archivoConfiguracion);
		for (String s : lineas) {
			String[] split = s.split(":");
			JLabel lbl = new JLabel("00 " + split[5]);
			lbl.setBounds(Integer.parseInt(split[1]),
					Integer.parseInt(split[2]), Integer.parseInt(split[3]),
					Integer.parseInt(split[4]));
			lbl.setFont(new Font("Dialog", Font.BOLD, 14));
			lbl.setOpaque(true);
			lbl.setForeground(Color.GREEN);
			lbl.setBackground(Color.BLACK);
			lbl.setHorizontalAlignment(SwingConstants.CENTER);
			lbl.setName(split[5]);
			add(lbl);
			getLblsValores().put(split[0], lbl);
		}
	}

	public ArrayList<String> readFile(String fileName) {
		ArrayList<String> configuraciones = new ArrayList<String>();
		try {
			FileReader fr = new FileReader("conf-img/" + fileName);
			BufferedReader br = new BufferedReader(fr);
			String strLine;
			while ((strLine = br.readLine()) != null) {
				if (!strLine.trim().equals("") && !strLine.startsWith("#"))
					configuraciones.add(strLine);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return configuraciones;
	}

	private HashMap<String, JLabel> getLblsValores() {
		if (lblsValores == null)
			lblsValores = new HashMap<String, JLabel>();
		return lblsValores;
	}

	public String getUnidades() {
		return unidades;
	}

	public void setUnidades(String unidades) {
		this.unidades = unidades;
	}

	public ChartConfiguration getChartConf() {
		return chartConf;
	}

	public void setChartConf(ChartConfiguration chartConf) {
		this.chartConf = chartConf;
	}

	public CsvManager getCsvManager() {
		return csvManager;
	}

	public void setCsvManager(CsvManager csvManager) {
		this.csvManager = csvManager;
	}
}

class ImageComponent extends JComponent {
	private static final long serialVersionUID = 1L;
	private Image image;

	public ImageComponent(String nombre) {
		try {
			File image2 = new File(nombre);
			image = ImageIO.read(image2);
			Dimension size = new Dimension(image.getWidth(null),
					image.getHeight(null));
			setPreferredSize(size);
			setMinimumSize(size);
			setMaximumSize(size);
			setSize(size);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void paintComponent(Graphics g) {
		if (image == null)
			return;

		g.drawImage(image, 0, 0, this);
	}
}